import { Context } from "koa"
import { DateRecord } from "./context"
export default class Tool {
    //生成数值得函数
    public static random(min:number,max:number,bool?:boolean,isFixed?:number):number {
        if (!bool) {
            return Math.floor(Math.random()*(max - min + 1)) + min
        } else {
            return Number(Math.random().toFixed(isFixed)) + (Math.floor(Math.random()*(max - min + 1)) + min )
        }
    }
      // 获取今日的日期字符串
    public static getCurrentDate(): string {
        let date:Date = new Date()
        let str:string = date.toLocaleDateString().replace(/\//g,'-')
        return str
    }
    public static async isExisted(ctx:Context,next:any) {
        let currentDate:string = Tool.getCurrentDate()
        let bool = await DateRecord.findAll({
            where: {
                currentDate
            }
        })
        if (bool.length === 0) {
            // @ts-ignore
            await DateRecord.create({currentDate})
            await next()
        } else {
            ctx.body = {
                code: 404,
                msg: "已经存在了"
            }
        }
    }

    public static getCurrentTime():string {
        let date:Date = new Date() // 日期对象
        let dateStr:string = date.toLocaleDateString().replace(/\//g,'-')
        let timeStr:string = date.toLocaleTimeString()
        return dateStr + '-' + timeStr
    }
}